package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        // 1.获取文件名
        String fileName = file.getOriginalFilename();
        // 2.截取后缀
        String extName = fileName.substring(fileName.lastIndexOf("."));
        // 3.使用UUID重新构建新的名字
        String uuidFileName = UUID.randomUUID().toString()+extName;
        // 2.构建文件存储的目录
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdir();
        }

        // 目标文件  目录+文件名   F:/reggie_img/fileName
        File targetFile = new File(dir,uuidFileName);
        // 把上传的文件拷贝到目标的文件上（本质上就是IO流的拷贝文件）
        file.transferTo(targetFile);
        return R.success(uuidFileName);
    }

    /*
        文件的下载
        目标：读取文件资源，像浏览器输出
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        // 1.找到目标文件
        File targetFile = new File(path,name);
        // 2.建立文件的输入流
        FileInputStream fileInputStream = new FileInputStream(targetFile);
        // 得到响应输出流
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] buf = new byte[1024];
        int length = 0;
        // 边读边写
        while ((length=fileInputStream.read(buf))!=-1){
            outputStream.write(buf,0,length);
        }
        fileInputStream.close();
    }
}
